package cn.kooki.app.duobao.ui.Activity.User;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.umeng.analytics.MobclickAgent;

import java.util.HashMap;

import butterknife.ButterKnife;
import butterknife.Bind;
import cn.jpush.android.api.JPushInterface;
import cn.kooki.app.duobao.R;
import cn.kooki.app.duobao.base.BaseActivity;
import cn.kooki.app.duobao.core.APIService;
import cn.kooki.app.duobao.core.MainFactory;
import cn.kooki.app.duobao.data.Bean.User.LoginResponse;
import cn.kooki.app.duobao.data.Bean.User.UserInfo;
import cn.kooki.app.duobao.data.Bean.base.BaseResponse;
import cn.kooki.app.duobao.data.bus.ErrorEvent;
import cn.kooki.app.duobao.data.bus.LoginChangeEvent;
import cn.kooki.app.duobao.data.bus.NetStatusEvent;
import cn.kooki.app.duobao.util.DESUtils;
import cn.kooki.app.duobao.util.SharePreferencesUtils;
import cn.kooki.app.duobao.util.StringUtils;
import cn.kooki.app.duobao.util.ToastUtils;
import cn.kooki.app.duobao.util.manager.LoginManager;
import de.greenrobot.event.EventBus;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * Created by xiong on 2015/11/27.
 */
public class RegActivity extends BaseActivity implements View.OnClickListener {
    @Bind(R.id.register_change)
    TextView registerChange;
    @Bind(R.id.mobile_tips)
    TextView mobileTips;
    @Bind(R.id.register_sent)
    TextView registerSent;
    @Bind(R.id.mobile_wrapper)
    RelativeLayout mobileWrapper;
    @Bind(R.id.register_verifycode)
    EditText registerVerifycode;
    @Bind(R.id.register_resend)
    TextView registerResend;
    @Bind(R.id.verifycode_wrapper)
    RelativeLayout verifycodeWrapper;
    @Bind(R.id.register_password)
    EditText registerPassword;
    @Bind(R.id.pass_wrapper)
    RelativeLayout passWrapper;
    @Bind(R.id.register_error)
    TextView registerError;
    @Bind(R.id.register_submit)
    Button registerSubmit;
    @Bind(R.id.register_agreement)
    CheckBox registerAgreement;
    @Bind(R.id.register_terms)
    TextView registerTerms;
    @Bind(R.id.register_policy1)
    TextView registerPolicy1;
    @Bind(R.id.register_policy2)
    TextView registerPolicy2;
    @Bind(R.id.register_root)
    LinearLayout registerRoot;
    @Bind(R.id.mask)
    View mask;
    @Bind(R.id.top_back)
    ImageButton topBack;
    @Bind(R.id.top_text_center)
    TextView topTextCenter;
    @Bind(R.id.top_cart)
    ImageButton topCart;
    @Bind(R.id.action_edit)
    TextView actionEdit;
    @Bind(R.id.toolbar)
    RelativeLayout toolbar;
    @Bind(R.id.register_mobile)
    EditText registerMobile;
    @Bind(R.id.change_mobile_wrapper)
    LinearLayout changeMobileWrapper;

    private int mincount = 90;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {
                mincount--;
                registerResend.setText(mincount + "秒后重新发送");
                if (mincount <= 0) {
                    mincount = 90;
                    handler.sendEmptyMessageDelayed(1, 1000);
                } else {
                    handler.sendEmptyMessageDelayed(0, 1000);
                }
            } else if (msg.what == 1) {
                registerResend.setEnabled(true);
                registerResend.setText(R.string.register_resend);
            }
        }
    };
    private String moblie;

    @Override
    protected void setToolbar() {

    }

    @Override
    protected void setLayoutContentView() {
        setContentView(R.layout.register_activity_by_phone);
        ButterKnife.bind(this);


    }

    @Override
    protected void afterView() {
        topBack.setVisibility(View.VISIBLE);
        topBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideSoftKeyBoard();
                finish();
            }
        });
        topTextCenter.setText(R.string.register);
        topTextCenter.setVisibility(View.VISIBLE);
        registerSubmit.setOnClickListener(this);
        registerChange.setOnClickListener(this);
        registerResend.setOnClickListener(this);

    }


    public void onEventMainThread(ErrorEvent errorEvent) {
        errorEvent.getException().printStackTrace();
    }

    @Override
    public void onEventMainThread(NetStatusEvent netStatusEvent) {
        super.onEventMainThread(netStatusEvent);
    }


    @Override
    public void onClick(View v) {
        if (v == registerSubmit) {

            if (checkFrom(false)) {
                getmoblie();
                register(moblie);
            }
        }

        if (v == registerChange) {
            registerMobile.setVisibility(View.VISIBLE);
            changeMobileWrapper.setVisibility(View.GONE);
        }
        if (v == registerResend) {
            getmoblie();
            if (checkFrom(true)) {

                MainFactory.getApiInstance().checkUser(moblie, new Callback<BaseResponse>() {
                    @Override
                    public void success(BaseResponse baseResponse, Response response) {
                        if (baseResponse.getStatus() != 0) {
                            getValidateCode();
                        } else {
                            showToastMessage("该手机已注册");
                        }
                    }

                    @Override
                    public void failure(RetrofitError error) {
                        showToastErrorMessage(error.getMessage());
                    }
                });
            }
        }
    }

    private void getValidateCode() {
        registerResend.setEnabled(false);
        handler.sendEmptyMessage(0);

        MainFactory.getApiInstance().getcode(moblie, new Callback<BaseResponse>() {
            @Override
            public void success(BaseResponse baseResponse, Response response) {

            }

            @Override
            public void failure(RetrofitError error) {

            }
        });
    }

    private void getmoblie() {
        moblie = "";
        if (registerMobile.getVisibility() == View.VISIBLE) {
            moblie = registerMobile.getText().toString();
        } else {
            moblie = registerSent.getText().toString();
        }
    }

    private void register(String moblie) {
        showLoading(getString(R.string.register_loadingstring));
        APIService apiInstance = MainFactory.getApiInstance();
        HashMap<String, Object> other = new HashMap<>();
        other.put("username", moblie);
        other.put("password", DESUtils.MD5(registerPassword.getText().toString()));
        other.put("mobile", moblie);
        other.put("code", registerVerifycode.getText().toString());
        apiInstance.register(1, 4, other, new Callback<LoginResponse>() {
            @Override
            public void success(LoginResponse s, Response response) {
                showToastMessage(s.getMsg());
                if (s.getStatus() == 0 && s.getData() != null) {
                    SharePreferencesUtils.putBoolean(RegActivity.this, SharePreferencesUtils.ISLOGIN, true);
                    UserInfo info = s.getData();
                    SharePreferencesUtils.putUserinfo(RegActivity.this, info);
                    LoginChangeEvent loginChangeEvent = new LoginChangeEvent();
                    loginChangeEvent.islogin = true;
                    MobclickAgent.onProfileSignIn(info.getUid());
                    JPushInterface.setAlias(getApplication(), info.getUid(), null);
                    EventBus.getDefault().post(loginChangeEvent);
                    LoginManager.checkIsNew(info.getUid());
                    finish();
                }
                dismissLoading();
            }

            @Override
            public void failure(RetrofitError error) {
                showToastMessage(getString(R.string.network_error));
                dismissLoading();
            }
        });
    }


    private boolean checkFrom(boolean isgetcode) {
//        if (registerMobile.getVisibility() == View.VISIBLE && TextUtils.isEmpty(registerMobile.getText().toString())) {
//            ToastUtils.showShortMessage(getResources().getString(R.string.mobile_is_empty), this);
//            return false;
//        }
//        if (registerMobile.getVisibility() == View.GONE && TextUtils.isEmpty(registerSent.getText().toString())) {
//            ToastUtils.showShortMessage(getResources().getString(R.string.mobile_is_empty), this);
//            return false;
//        }
        if (TextUtils.isEmpty(registerMobile.getText().toString())) {
            showToastMessage(getString(R.string.mobile_is_empty));
            return false;
        }
        if (!StringUtils.isMobile(registerMobile.getText().toString())) {
            showToastMessage(getString(R.string.mobile_is_error));
            return false;
        }
        if (!isgetcode) {
            if (TextUtils.isEmpty(registerPassword.getText().toString()) || registerPassword.getText().toString().length() < 6) {
                ToastUtils.showShortMessage(getResources().getString(R.string.mobile_wrong_password), this);
                return false;
            }
            if (TextUtils.isEmpty(registerVerifycode.getText().toString())) {
                showToastMessage(getString(R.string.mobile_verifycode_empty));
                return false;
            }
        }
        return true;
    }


}
